import { Order, OrderItem, Product, CartItem, Address, ApiResponse, Pagination} from '../types';
import { STORAGE_KEYS, getStorageData, setStorageData } from '../utils/storage';
import { checkAuth, getCurrentUser } from './userService';

// 生成UUID（简化版）
const generateOrderUUID = (): string => {
  const date = new Date();
  const dateStr = date.getFullYear().toString() +
    (date.getMonth() + 1).toString().padStart(2, '0') +
    date.getDate().toString().padStart(2, '0');
  const randomStr = Math.random().toString(36).substr(2, 6).toUpperCase();
  return `ORD${dateStr}-${randomStr}`;
};

const generateOrderItemUUID = (): string => {
  return 'order_item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// ===== 订单查询功能 =====

export interface OrderListQuery {
  page?: number;
  pageSize?: number;
  status?: 'pending' | 'completed' | 'cancelled';
}

export interface OrderListResponse {
  orders: Order[];
  pagination: Pagination;
}

/**
 * 获取用户订单列表
 */
export const getOrders = async (query: OrderListQuery = {}): Promise<ApiResponse<OrderListResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;
    const { page = 1, pageSize = 20, status } = query;

    // 获取所有订单，筛选当前用户的
    let allOrders = getStorageData<Order>(STORAGE_KEYS.ORDERS);
    let userOrders = allOrders.filter(order => order.userId === currentUser.id);

    // 状态筛选
    if (status) {
      userOrders = userOrders.filter(order => order.status === status);
    }

    // 按创建时间倒序排列
    userOrders.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

    // 分页
    const total = userOrders.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedOrders = userOrders.slice(startIndex, endIndex);

    return {
      code: 200,
      message: '获取订单列表成功',
      data: {
        orders: paginatedOrders,
        pagination: {
          current: page,
          pageSize,
          total
        }
      }
    };

  } catch (error) {
    console.error('获取订单列表失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 获取订单详情
 */
export const getOrderById = async (orderId: string): Promise<ApiResponse<{ order: Order }>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    if (!orderId) {
      return {
        code: 400,
        message: '订单ID不能为空',
        data: null
      };
    }

    const orders = getStorageData<Order>(STORAGE_KEYS.ORDERS);
    const order = orders.find(o => o.id === orderId);

    if (!order) {
      return {
        code: 404,
        message: '订单不存在',
        data: null
      };
    }

    // 检查是否属于当前用户
    if (order.userId !== currentUser.id) {
      return {
        code: 403,
        message: '无权查看此订单',
        data: null
      };
    }

    return {
      code: 200,
      message: '获取订单详情成功',
      data: {
        order
      }
    };

  } catch (error) {
    console.error('获取订单详情失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 订单创建功能 =====

export interface CreateOrderRequest {
  addressId: string;
  cartItemIds?: string[]; // 从购物车创建订单时提供
  directItems?: Array<{   // 直接购买时提供
    productId: string;
    quantity: number;
  }>;
}

export interface CreateOrderResponse {
  order: Order;
}

/**
 * 创建订单
 */
export const createOrder = async (params: CreateOrderRequest): Promise<ApiResponse<CreateOrderResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;
    const { addressId, cartItemIds, directItems } = params;

    // 参数验证
    if (!addressId) {
      return {
        code: 400,
        message: '收货地址ID不能为空',
        data: null
      };
    }

    if ((!cartItemIds || cartItemIds.length === 0) && (!directItems || directItems.length === 0)) {
      return {
        code: 400,
        message: '必须指定购物车商品或直接购买商品',
        data: null
      };
    }

    // 验证收货地址
    const addresses = getStorageData<Address>(STORAGE_KEYS.ADDRESSES);
    const shippingAddress = addresses.find(addr => addr.id === addressId && addr.userId === currentUser.id);

    if (!shippingAddress) {
      return {
        code: 404,
        message: '收货地址不存在',
        data: null
      };
    }

    // 获取订单商品信息
    let orderItems: OrderItem[] = [];
    let totalAmount = 0;

    if (cartItemIds && cartItemIds.length > 0) {
      // 从购物车创建订单
      const cartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);
      const selectedCartItems = cartItems.filter(item =>
        item.userId === currentUser.id &&
        cartItemIds.includes(item.id) &&
        item.selected
      );

      if (selectedCartItems.length === 0) {
        return {
          code: 400,
          message: '没有找到有效的购物车商品',
          data: null
        };
      }

      // 验证商品状态和库存
      const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);

      for (const cartItem of selectedCartItems) {
        const product = products.find(p => p.id === cartItem.productId);

        if (!product || product.status !== 'active') {
          return {
            code: 400,
            message: `商品 ${cartItem.product.name} 已下架`,
            data: null
          };
        }

        if (product.stock < cartItem.quantity) {
          return {
            code: 400,
            message: `商品 ${product.name} 库存不足，当前库存：${product.stock}`,
            data: null
          };
        }

        const orderItem: OrderItem = {
          id: generateOrderItemUUID(),
          productId: product.id,
          product: product,
          quantity: cartItem.quantity,
          price: product.price // 使用当前价格
        };

        orderItems.push(orderItem);
        totalAmount += orderItem.price * orderItem.quantity;
      }
    } else if (directItems && directItems.length > 0) {
      // 直接购买
      const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);

      for (const item of directItems) {
        if (!item.productId || item.quantity <= 0) {
          return {
            code: 400,
            message: '商品ID和数量都是必填的，且数量必须大于0',
            data: null
          };
        }

        const product = products.find(p => p.id === item.productId);

        if (!product || product.status !== 'active') {
          return {
            code: 404,
            message: '商品不存在或已下架',
            data: null
          };
        }

        if (product.stock < item.quantity) {
          return {
            code: 400,
            message: `商品 ${product.name} 库存不足，当前库存：${product.stock}`,
            data: null
          };
        }

        const orderItem: OrderItem = {
          id: generateOrderItemUUID(),
          productId: product.id,
          product: product,
          quantity: item.quantity,
          price: product.price
        };

        orderItems.push(orderItem);
        totalAmount += orderItem.price * orderItem.quantity;
      }
    }

    // 创建订单
    const now = new Date().toISOString();
    const newOrder: Order = {
      id: generateOrderUUID(),
      userId: currentUser.id,
      status: 'pending',
      totalAmount,
      shippingAddress,
      items: orderItems,
      createdAt: now
    };

    // 更新商品库存和销量
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const updatedProducts = products.map(product => {
      const orderItem = orderItems.find(item => item.productId === product.id);
      if (orderItem) {
        return {
          ...product,
          stock: product.stock - orderItem.quantity,
          // 注意：只有支付完成后才增加销量
          updatedAt: now
        };
      }
      return product;
    });

    // 保存订单和更新库存
    const orders = getStorageData<Order>(STORAGE_KEYS.ORDERS);
    const updatedOrders = [...orders, newOrder];

    setStorageData(STORAGE_KEYS.ORDERS, updatedOrders);
    setStorageData(STORAGE_KEYS.PRODUCTS, updatedProducts);

    // 如果是从购物车创建的订单，清理购物车
    if (cartItemIds && cartItemIds.length > 0) {
      const cartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);
      const filteredCartItems = cartItems.filter(item =>
        !(item.userId === currentUser.id && cartItemIds.includes(item.id))
      );
      setStorageData(STORAGE_KEYS.CART_ITEMS, filteredCartItems);
    }

    return {
      code: 200,
      message: '订单创建成功',
      data: {
        order: newOrder
      }
    };

  } catch (error) {
    console.error('创建订单失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 订单支付功能 =====

/**
 * 支付订单
 */
export const payOrder = async (orderId: string): Promise<ApiResponse<{ order: Order }>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    if (!orderId) {
      return {
        code: 400,
        message: '订单ID不能为空',
        data: null
      };
    }

    const orders = getStorageData<Order>(STORAGE_KEYS.ORDERS);
    const orderIndex = orders.findIndex(o => o.id === orderId);

    if (orderIndex === -1) {
      return {
        code: 404,
        message: '订单不存在',
        data: null
      };
    }

    const order = orders[orderIndex];

    // 检查是否属于当前用户
    if (order.userId !== currentUser.id) {
      return {
        code: 403,
        message: '无权操作此订单',
        data: null
      };
    }

    // 检查订单状态
    if (order.status !== 'pending') {
      return {
        code: 400,
        message: '订单状态不正确，无法支付',
        data: null
      };
    }

    // 再次检查库存（防止并发问题）
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    for (const orderItem of order.items) {
      const product = products.find(p => p.id === orderItem.productId);
      if (!product || product.status !== 'active') {
        return {
          code: 400,
          message: `商品 ${orderItem.product.name} 已下架`,
          data: null
        };
      }
      // 注意：库存在创建订单时已经扣减，这里不需要再检查
    }

    // 更新订单状态
    const now = new Date().toISOString();
    const updatedOrder: Order = {
      ...order,
      status: 'completed',
      completedAt: now
    };

    orders[orderIndex] = updatedOrder;

    // 更新商品销量
    const updatedProducts = products.map(product => {
      const orderItem = order.items.find(item => item.productId === product.id);
      if (orderItem) {
        return {
          ...product,
          sales: product.sales + orderItem.quantity,
          updatedAt: now
        };
      }
      return product;
    });

    // 保存数据
    setStorageData(STORAGE_KEYS.ORDERS, orders);
    setStorageData(STORAGE_KEYS.PRODUCTS, updatedProducts);

    return {
      code: 200,
      message: '支付成功',
      data: {
        order: updatedOrder
      }
    };

  } catch (error) {
    console.error('支付订单失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 订单取消功能 =====

/**
 * 取消订单（恢复库存，设置为cancelled状态）
 */
export const cancelOrder = async (orderId: string): Promise<ApiResponse<{ order: Order }>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    if (!orderId) {
      return {
        code: 400,
        message: '订单ID不能为空',
        data: null
      };
    }

    const orders = getStorageData<Order>(STORAGE_KEYS.ORDERS);
    const orderIndex = orders.findIndex(o => o.id === orderId);

    if (orderIndex === -1) {
      return {
        code: 404,
        message: '订单不存在',
        data: null
      };
    }

    const order = orders[orderIndex];

    // 检查是否属于当前用户
    if (order.userId !== currentUser.id) {
      return {
        code: 403,
        message: '无权操作此订单',
        data: null
      };
    }

    // 检查订单状态（只能取消待支付的订单）
    if (order.status !== 'pending') {
      return {
        code: 400,
        message: '只能取消待支付的订单',
        data: null
      };
    }

    // 恢复库存
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const updatedProducts = products.map(product => {
      const orderItem = order.items.find(item => item.productId === product.id);
      if (orderItem) {
        return {
          ...product,
          stock: product.stock + orderItem.quantity, // 恢复库存
          updatedAt: new Date().toISOString()
        };
      }
      return product;
    });

    // 更新订单状态为cancelled
    const cancelledOrder: Order = {
      ...order,
      status: 'cancelled'
    };

    orders[orderIndex] = cancelledOrder;

    // 保存数据
    setStorageData(STORAGE_KEYS.ORDERS, orders);
    setStorageData(STORAGE_KEYS.PRODUCTS, updatedProducts);

    return {
      code: 200,
      message: '订单已取消，库存已恢复',
      data: {
        order: cancelledOrder
      }
    };

  } catch (error) {
    console.error('取消订单失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};